package com.ficus.road.maintain.handler.smartdecision.handlers.highway;

import com.ficus.road.maintain.core.model.Hit;
import com.ficus.road.maintain.core.model.smartnew.SmartDecisionHighwayRequest;
import com.ficus.road.maintain.core.model.smartnew.SmartDecisionRequest;
import com.ficus.road.maintain.core.model.smartnew.SmartDecisionResponse;
import com.ficus.road.maintain.core.model.smartnew.SmartRoadDisease;
import com.ficus.road.maintain.dao.HitDao;
import com.ficus.road.maintain.dao.SmartRoadDiseaseDao;
import com.ficus.road.maintain.handler.smartdecision.enums.SmartDecisionStrategyEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xiawen yang
 * @date 2022/7/21 下午1:57
 */
@Component
@Order(0)
@RequiredArgsConstructor
public class SmartDecisionHighwayDiscoveryHandler extends AbstractSmartDecisionHighwayHandler {

    private static final SmartDecisionStrategyEnum STRATEGY = SmartDecisionStrategyEnum.HIGHWAY_DISCOVERY;
    private final SmartRoadDiseaseDao smartRoadDiseaseDao;
    private final HitDao hitDao;

    @Override
    public SmartDecisionResponse doHandle(SmartDecisionRequest request, SmartDecisionResponse response) {
        // 前处理
        preProcess(response);
        SmartDecisionHighwayRequest highwayRequest = (SmartDecisionHighwayRequest) request;
        return strategySmartDecisionService.smartDecisionCalculate(STRATEGY, highwayRequest.getParams(), response);
    }

    /**
     * 智慧决策前置环节
     */
    private void preProcess(SmartDecisionResponse response) {
        List<SmartRoadDisease> allRoadDisease = smartRoadDiseaseDao.findAll();
        allRoadDisease.stream().map(this::completeHitAttr).forEach(smartRoadDiseaseDao::saveOrUpdate);
        response.getSmartDiscoveryResponse().setSmartDetectCount(allRoadDisease.size());
    }

    private SmartRoadDisease completeHitAttr(SmartRoadDisease disease) {
        Hit hit = hitDao.fetch(disease.getHitId());
        disease.setType(hit.getType());
        disease.setFirstHitTime(hit.getFirstHitTime());
        disease.setPicUrl(hit.getAttrs().getSceneImage());
        disease.setRoadType(hit.getAttrs().getRoadType());
        return disease;
    }
}
